package com.jing.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jing.mapper.ReadingRoomsMapper;
import com.jing.mapper.SensorMapper;
import com.jing.pojo.PageBean;
import com.jing.pojo.ReadingRooms;
import com.jing.pojo.SensorConfig;
import com.jing.service.ReadingRoomsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 陈书憬
 * @version 1.0
 * 2024/9/17
 */
@Service
public class ReadingRoomsServiceImpl implements ReadingRoomsService {
    @Autowired
    private ReadingRoomsMapper readingRoomsMapper;

    @Autowired
    private SensorMapper sensorMapper;

    @Override
    public PageBean<ReadingRooms> list(Integer pageNum, Integer pageSize, String name, String type) {
        //1.创建PageBean对象
        PageBean<ReadingRooms> pb = new PageBean<>();

        //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum, pageSize);


        List<ReadingRooms> as = readingRoomsMapper.list(name, type);
        //Page中提供了方法,可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
        Page<ReadingRooms> p = (Page<ReadingRooms>) as;

        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public List<ReadingRooms> categoryList() {
        return readingRoomsMapper.categoryList();
    }

    @Override
    public void add(ReadingRooms readingRooms) {

        //补充属性值
        readingRooms.setCreatedTime(String.valueOf(LocalDateTime.now()));
        readingRooms.setUpdatedTime(String.valueOf(LocalDateTime.now()));

        readingRoomsMapper.add(readingRooms);

        int roomId = readingRoomsMapper.getRoomId(readingRooms.getName());

        SensorConfig sensorConfig = new SensorConfig();
        sensorConfig.setRoomId(roomId);
        sensorConfig.setRoomName(readingRooms.getName());
        sensorConfig.setCreateTime(String.valueOf(LocalDateTime.now()));
        sensorMapper.add(sensorConfig);
    }

    @Override
    public void update(ReadingRooms readingRooms) {
        readingRooms.setUpdatedTime(String.valueOf(LocalDateTime.now()));
        readingRoomsMapper.update(readingRooms);
    }

    @Override
    public void deleteById(Integer id) {
        readingRoomsMapper.deleteById(id);
        sensorMapper.deleteById(id);
    }

    @Override
    public void updateState(Long id, Boolean state) {
        readingRoomsMapper.updateState(id, state);
    }

    @Override
    public List<ReadingRooms> listNoPage() {


        List<ReadingRooms> L = readingRoomsMapper.listNoPage();
        return L;
    }


}
